using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using HybridCLR.Editor;
using System;
using System.Reflection;
using System.Linq;

namespace cframework
{
    [CreateAssetMenu(menuName = "cframework/HybridclrAssemblySetting")]
    public class HybridclrAssemblySetting : ScriptableObject
    {
        //[Title("HybridclrAssemblySetting")]
        public AssemblyDefinitionAsset[] hotUpdateAssemblyDefinitions;
        public string[] hotUpdateAssemblies;
        public AssemblyDefinitionAsset[] patchAssemblyDefinitions;
        public string[] patchAOTAssemblies;

        [ContextMenu("Enable")]
        public void Enable()
        {
            Set(true);
        }

        public void Set(bool enable)
        {
            if (enable)
            {
                SettingsUtil.HybridCLRSettings.enable = enable;
                SettingsUtil.HybridCLRSettings.hotUpdateAssemblyDefinitions = hotUpdateAssemblyDefinitions;
                SettingsUtil.HybridCLRSettings.hotUpdateAssemblies = hotUpdateAssemblies;
                var tempPatchAOTAssemblies = System.Array.ConvertAll(patchAssemblyDefinitions, a => a.name).Concat(patchAOTAssemblies).ToArray();
                SettingsUtil.HybridCLRSettings.patchAOTAssemblies = CheckAndConvert(tempPatchAOTAssemblies);
                HybridCLR.Editor.Settings.HybridCLRSettings.Save();
            }
            else
            {
                Disable();
            }

        }

        [MenuItem("cframework/HybridcCLR/Disable")]
        public static void Disable()
        {
            SettingsUtil.HybridCLRSettings.enable = false;
            SettingsUtil.HybridCLRSettings.hotUpdateAssemblyDefinitions = new AssemblyDefinitionAsset[0];
            SettingsUtil.HybridCLRSettings.hotUpdateAssemblies = new string[0];
            SettingsUtil.HybridCLRSettings.patchAOTAssemblies = new string[0];
            HybridCLR.Editor.Settings.HybridCLRSettings.Save();
        }

        
        string[] CheckAndConvert(string[] dllNames, string addExt = ".dll")
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            dllNames = System.Array.ConvertAll(dllNames, a => a.Replace(".dll", ""));

            return dllNames.Where(a => System.Array.Exists(assemblies, b => b.GetName().Name == a)).ToList().ConvertAll(a => a + addExt).ToArray();
        }

        [ContextMenu("Test")]
        void Abc()
        {
            var tempPatchAOTAssemblies = System.Array.ConvertAll(patchAssemblyDefinitions, a => a.name).Concat(patchAOTAssemblies).ToArray();
            CheckAndConvert(tempPatchAOTAssemblies);

            Debug.LogError("test1 " + string.Join(",", tempPatchAOTAssemblies));
            Debug.LogError("test2 " + string.Join(",", CheckAndConvert(tempPatchAOTAssemblies)));
        }
    }
}